package main

import (
	"common/config"
	"common/initialize"
	"equipment_server/grpc"
	"equipment_server/service"
	"equipment_server/service/websocket"
	grpc2 "google.golang.org/grpc"
	"log"
	"net/http"
	"time"
)

func setupHttpServer() {
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		websocket.ServeWs(websocket.GlobalHub, w, r)
	})
	log.Println("Starting HTTP server on :8085")
	err := http.ListenAndServe(":8085", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func main() {
	config.InitViper()
	initialize.InitNachos(func() {
		initialize.InitMysql()
		initialize.InitRedis()
		initialize.InitEs()
		initialize.InitMonGoDb()
	})
	initialize.InitMysql()
	initialize.InitRedis()
	initialize.InitEs()
	initialize.InitLog()
	initialize.InitMonGoDb()
	initialize.DeviceSubscription()
	service.SubscribeDeviceResponses()

	// Start the HTTP server for WebSocket
	go setupHttpServer()

	// 设置定时任务，每天凌晨2点执行 清除1年之前的数据
	go func() {
		for {
			now := time.Now()
			next := now.Add(24 * time.Hour)
			next = time.Date(next.Year(), next.Month(), next.Day(), 2, 0, 0, 0, next.Location())
			t := time.NewTimer(next.Sub(now))
			<-t.C
			service.CleanHealthData()
		}
	}()
	grpc.RegisterEquipmentGrpc("127.0.0.1", 9992, func(server *grpc2.Server) {
		service.EquipmentRegister(server)
	})
}
